#include<iostream>
#include<cstring>
#include<queue>

using namespace std;

const int maxn = 110;

int g[maxn][maxn];
int d[maxn][maxn];
int n, m;

#define CHECK(x, y) (x < n && x >= 0 && y < m && y >= 0)

struct node {
    int x;
    int y;
};

int dir[4][2]{
        {-1, 0},
        {0,  -1},
        {1,  0},
        {0,  1},
};

int bfs() {

    queue<node> q;

    node start, temp;

    start = {0, 0};

    d[0][0] = 0;

    q.push(start);
    while (!q.empty()) {
        start = q.front();
        q.pop();
        for (int i = 0; i < 4; i++) {
            int newx = start.x + dir[i][0];
            int newy = start.y + dir[i][1];

            if (CHECK(newx, newy) && g[newx][newy] == 0 && d[newx][newy] == -1) {
                g[newx][newy] = 1;
                d[newx][newy] = d[start.x][start.y] + 1;
                temp = {newx, newy};
                q.push(temp);
            }

        }
    }

    return d[n - 1][n -1    ];
}

int main() {

    memset(d, -1, sizeof d);

    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            scanf("%d", &g[i][j]);
        }
    }

    printf("%d\n", bfs());

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            printf("%d\t" , d[i][j]) ;
        }
        printf("\n");
    }

    return 0;
}